package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.admin.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.*;
import com.jmp.feign.GoodsFeign;
import com.jmp.feign.SunCodeFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.dto.ConvertUtils;
import one.stand.dto.GoodsTypeDto;
import one.stand.dto.PageResponse2;
import one.stand.dto.SeeRecordDto;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiAdminMapper;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.util.DateUtil;
import one.stand.util.OneListUtil;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "产品管理")
@RestController
@RequestMapping("adminApi/goods")
@Slf4j
public class GoodsController {

    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;

    @Autowired
    private JdbcTemplate myJdbcTemplate;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;

    @Autowired
    private GoodsApiAdminMapper goodsApiAdminMapper;

    @ApiOperation("商品列表")
    @PostMapping("list")
    @SecurityAuthCheck
    public ResultModel<GoodsListResponse> list(@RequestBody GoodsListRequest request) {
        String companyNameLike = SqlUtil.like(request.getCompanyName());
        String nameLike = SqlUtil.like(request.getGoodsName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> goodsList = goodsApiAdminMapper.selectPlatformTypeList(request.getType(), companyNameLike, nameLike, request.getTypeId(), CompanyBaseService.LABEL_SUPPLIER);

        PageResponse2<GoodsListResponse.Goods> goodsPageResponse2 = ConvertUtils.page2(goodsList, goods -> {
            GoodsType goodsType = goodsTypeService.get(goods.getGoodstypeId());
            Company company = companyBaseService.getById(goods.getCompanyId());
            List<GoodsTypeDto> platformTypes = goodsBaseService.getTypes(goods.getGoodsId());
            List<Integer> platformTypeIds = ConvertUtils.list(platformTypes, GoodsTypeDto::getTypeId);
            List<String> platformTypeNames = ConvertUtils.list(platformTypes, GoodsTypeDto::getGroupName);
            String qrCode = StringUtils.EMPTY;
            List<GoodSpec> getSpecs = goodsBaseService.getSpecs(goods.getGoodsId());
            if (OneListUtil.isNotEmpty(getSpecs)) {
                BusinessCard businessCard = businessCardBaseService.getByUserId(company.getUserId());
                ResultModel<SunCodeGoodsResponse> codeGoodsResponseResultModel = sunCodeFeign.goods(SunCodeGoodsRequest.builder().specId(getSpecs.get(0).getSpecId()).cardId(businessCard.getCardId()).build());
                if (codeGoodsResponseResultModel.isSuccess()) {
                    qrCode = codeGoodsResponseResultModel.getData().getCodeUrl();
                }
            }

            SeeRecordDto seeRecordDto = seeRecordPublicMapper.select(SeeRecordEnums.PRODUCT.getCode(), goods.getGoodsId());

            return GoodsListResponse.Goods.builder()
                    .goodsId(goods.getGoodsId())
                    .photo(goodsPhotoService.getPath(goods.getGoodsId()))
                    .goodsName(goods.getGoodsName())
                    .goodsPlatformTypeId(platformTypeIds)
                    .goodsPlatformTypeName(platformTypeNames)
                    .goodsTypeName(goodsType.getGroupName())
                    .companyName(company.getCompanyName())
                    .createTime(DateUtil.format(DateUtil.formatter, goods.getCreateTime()))
                    .popularityLevel(goods.getPopularityLevel())
                    .popularityNum(Objects.nonNull(seeRecordDto) ? seeRecordDto.getCountPopularity() : 0)
                    .popularityAdd(Objects.nonNull(seeRecordDto) ? seeRecordDto.getCountPopularityAdd() : 0)
                    .qrCode(qrCode)
                    .build();
        });

        List<GoodsType> list = goodsApiAdminMapper.selectSelectTypeList(GoodsTypeService.PLATFORM_COMPANY_ID, false);
        List<GoodsListResponse.Type> types = ConvertUtils.list(list, type -> GoodsListResponse.Type.builder()
                .goodstypeId(type.getGoodstypeId())
                .name(type.getName())
                .parentId(type.getParentId())
                .groupName(type.getGroupName())
                .build());

        GoodsListResponse response = GoodsListResponse.builder()
                .goodsList(goodsPageResponse2)
                .typeList(types)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("编辑平台分类")
    @PostMapping("platform/type/edit")
    @SecurityAuthCheck
    public ResultModel platformTypeEdit(@RequestBody GoodsPlatformTypeEditRequest request) {

        goodsFeign.platformTypeUpdate(GoodsPlatformTypeUpdateRequest.builder()
                .goodsId(request.getGoodsId())
                .typeIds(request.getTypeId())
                .popularityLevel(request.getPopularityLevel())
                .build());

        return ResultModel.success();
    }


    @ApiOperation("取消平台分类")
    @PostMapping("platform/type/remove")
    @SecurityAuthCheck
    public ResultModel platformTypeRemove(@RequestBody GoodsPlatformTypeRemoveRequest request) {

        goodsFeign.platformTypeDelete(GoodsPlatformTypeDeleteRequest.builder()
                .goodsId(request.getGoodsId())
                .build());

        return ResultModel.success();
    }

    @ApiOperation("人气值")
    @PostMapping("popularity/add")
    @SecurityAuthCheck
    public ResultModel popularityAdd(@RequestBody GoodsPopularityAddRequest request) {

        SeeRecordDto seeRecordDto = seeRecordPublicMapper.select(SeeRecordEnums.PRODUCT.getCode(), request.getGoodsId());
        if (Objects.nonNull(seeRecordDto)) {
            seeRecordPublicMapper.updateCountPopularityAdd(seeRecordDto.getId(), request.getNum());
        } else {
            seeRecordPublicMapper.saveInit(SeeRecordEnums.PRODUCT.getCode(), request.getGoodsId(), request.getNum());
        }

        return ResultModel.success();
    }

    @ApiOperation("下拉列表")
    @PostMapping("type/select")
    @SecurityAuthCheck
    public ResultModel<GoodsTypeSelectResponse> list(@RequestBody GoodsTypeSelectRequest request) {
        List<GoodsType> list = goodsApiAdminMapper.selectSelectTypeList(request.getCompanyId(), false);

        List<GoodsTypeSelectResponse.Type> types = ConvertUtils.list(list, type -> GoodsTypeSelectResponse.Type.builder()
                .goodstypeId(type.getGoodstypeId())
                .name(type.getName())
                .parentId(type.getParentId())
                .build());

        GoodsTypeSelectResponse response = GoodsTypeSelectResponse.builder().types(types).build();
        return ResultModel.success(response);
    }

    @ApiOperation("下拉列表")
    @GetMapping("select")
    @SecurityAuthCheck
    public ResultModel<GoodsSelectResponse> list(GoodsSelectRequest request) {

        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(1, 10);//默认取10个
        List<Goods> goodsModels = goodsApiAdminMapper.selectList(nameLike);

        List<GoodsSelectResponse.Goods> goods = ConvertUtils.list(goodsModels, goodsModel -> {
            GoodsSelectResponse.Goods goods1 = new GoodsSelectResponse.Goods();
            goods1.setId(goodsModel.getGoodsId());
            goods1.setName(goodsModel.getGoodsName());
            return goods1;
        });

        GoodsSelectResponse response = new GoodsSelectResponse();
        response.setGoods(goods);
        return ResultModel.success(response);
    }

    @ApiOperation("下拉列表-非代理商品、分类搜索")
    @GetMapping("select2")
    @SecurityAuthCheck
    public ResultModel<GoodsSelect2Response> select2(GoodsSelect2Request request) {

        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(1, request.getPageSize());
        List<Goods> goodsModels = goodsApiAdminMapper.selectSelectList(nameLike, request.getCategoryId());

        List<GoodsSelect2Response.Goods> goods = ConvertUtils.list(goodsModels, goodsModel -> {
            Company company = companyBaseService.getById(goodsModel.getCompanyId());
            return GoodsSelect2Response.Goods.builder()
                    .id(goodsModel.getGoodsId())
                    .name(goodsModel.getGoodsName())
                    .photo(goodsPhotoService.getPath(goodsModel.getGoodsId()))
                    .companyName(company.getCompanyName())
                    .build();
        });

        GoodsSelect2Response response = new GoodsSelect2Response();
        response.setGoods(goods);
        return ResultModel.success(response);
    }

    @ApiOperation("删除导入商品")
    @PostMapping("import/delete")
    @SecurityAuthCheck
    public ResultModel goodsImportDelete(GoodsImportRequest request) {
        goodsFeign.deleteImport(GoodsDeleteImportRequest.builder().companyId(request.getCompanyId()).build());
        return ResultModel.success();
    }

    @ApiOperation("导入商品")
    @PostMapping("copy")
    @SecurityAuthCheck
    public ResultModel copy(GoodsCopyRequest request) {
        String sql = "SELECT" +
                " a.ProductName as 商品名称," +
                " a.categoryName as 商品分类," +
                " d.Description as 详情," +
                " IFNULL(a.VRUrl,a.VRUrl2) as VR," +
                " a.VideoPath as 视频," +
                " concat(" +
                " a.ImagePath,'/1.png,'," +
                " a.ImagePath,'/2.png,'," +
                " a.ImagePath,'/3.png,'," +
                " a.ImagePath,'/4.png,'," +
                " a.ImagePath,'/5.png' " +
                " ) as 图片," +
                " IFNULL(e.Version,'默认') as 规格名称," +
                " IF(ISNULL(e.Color) and ISNULL(e.Size),'默认', CONCAT(IFNULL(e.Color,''),IFNULL(e.Size,''))) as 子规格名称," +
                " e.Stock as 规格库存," +
                " if(e.SalePrice>=21474836,e.SalePrice,e.SalePrice*100) as 规格价格," +
                " a.Id " +
                " FROM" +
                " (SELECT a.Id,a.ProductName,a.VRUrl,a.VRUrl2," +
                " if(locate('http://',a.VideoPath)=0,concat('http://storage.hongmushichang.com',a.VideoPath),a.VideoPath) as VideoPath," +
                " if(locate('http://',a.ImagePath)=0,concat('http://storage.hongmushichang.com',a.ImagePath),a.ImagePath) as ImagePath," +
                " IFNULL(if(isNull(f.ProductId), concat( h.`Name`, '>', g.NAME ), f.categoryName),'其他>其他') as categoryName" +
                " from Hmsc_Products a " +
                " LEFT JOIN (SELECT f.ProductId,concat( c.`Name`, '>', b.NAME ) as categoryName " +
                " from Hmsc_ProductShopCategories f" +
                " LEFT JOIN Hmsc_ShopCategories b ON b.id = f.ShopCategoryId" +
                " LEFT JOIN Hmsc_ShopCategories c ON c.id = b.ParentCategoryId" +
                " WHERE c.id is not null" +
                " GROUP BY f.ProductId" +
                " )f on f.ProductId = a.Id" +
                " LEFT JOIN Hmsc_Categories g ON g.id = a.CategoryId" +
                " LEFT JOIN Hmsc_Categories h ON h.id = g.ParentCategoryId" +
                " where a.ShopId = " + request.getShopId() +
                " and a.SaleStatus = 1 and a.IsDeleted = 0 and f.ProductId is not null) a " +
                "" +
                " LEFT JOIN Hmsc_ProductDescriptions d ON d.ProductId = a.Id" +
                " LEFT JOIN Hmsc_SKUs e ON e.ProductId = a.Id" +
                "";
        List<Map<String, Object>> listob = myJdbcTemplate.queryForList(sql);

        goodsFeign.deleteImport(GoodsDeleteImportRequest.builder().companyId(request.getCompanyId()).build());

        if (OneListUtil.isNotEmpty(listob)) {
            List<List<String>> los = Lists.newArrayListWithExpectedSize(listob.size());
            List<String> lo;
            for (Map<String, Object> stringObjectMap : listob) {
                lo = ConvertUtils.list(Lists.newArrayList(stringObjectMap.values()), obj -> Objects.nonNull(obj) ? String.valueOf(obj) : null);
                los.add(lo);
            }
            OneListUtil.executeGroup(los,
                    list -> goodsFeign.saveImport(GoodsSaveImportRequest.builder().companyId(request.getCompanyId()).lo(list).build()),
                    100);
        }

        return ResultModel.success();
    }
}
